﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;
using System.Collections;

namespace ZBZH_Manage_Order.Controllers.SystemSettings
{
    public class WaltSetController : BaseController
    {
        //
        // GET: /WaltSet/

        ZHHQSERVICE.Service1Client zhhqser = new ZHHQSERVICE.Service1Client();
        // 操作员
        protected Model.View_OperUser operUser;

        public ActionResult Index()
        {
            return View();
        }


        #region 获取钱包信息列表
        /// <summary>
        /// 获取钱包信息列表
        /// </summary>
        /// <returns></returns>
        public ActionResult getgrid(JqGridParam jqgridparam)
        {
            try
            {
                List<Order_Walt_SA> List = new List<Order_Walt_SA>();
                List<Model.Order_Walt_T> list = new List<Model.Order_Walt_T>();
                string result = SRS.GetOrder_Walt(YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    list = ParseClass<Model.Order_Walt_T>.JsonList(jieguo);//解析返回的结果
                    foreach (Model.Order_Walt_T item in list)
                    {
                        try
                        {
                            
                        int max = int.Parse(item.WaltMax);
                        double a = max * 0.01;
                        item.WaltMax = a.ToString();
                        }
                        catch (Exception)
                        {
                            item.WaltMax = "0";
                        }
                    }
                List<Model.Order_Pay_T> List1 = new List<Model.Order_Pay_T>();
                string result2 = SRS.GetOrder_Pay(YZM, 1);
                JObject searcho2 = JObject.Parse(result2);//将服务返回的结果进行优化
                string bs2 = searcho2["BS"].ToString();//获取返回结果是否正常标识
                if (bs2 == "1")//返回结果正常
                {
                    IList<JToken> jieguo2 = searcho2["rows"].Children().ToList();//解析返回的结果
                    List1 = ParseClass<Model.Order_Pay_T>.JsonList(jieguo2);//解析返回的结果
                    //查询支付方式
                    foreach (var item1 in list)
                    {
                        Order_Walt_SA so = new Order_Walt_SA();
                        for (int i = 0; i < List1.Count; i++)
                        {
                            if (item1.WaltRec == List1[i].PayID)
                            {

                                so.PayName = List1[i].PayName;
                                so.MapUsing = "";
                                if (item1.WaltUsing.Substring(0, 1) == "1")
                                {
                                    so.MapUsing = "充值";
                                }
                                if (item1.WaltUsing.Substring(1, 1) == "1")
                                {
                                    if (so.MapUsing != "")
                                    {
                                        so.MapUsing += ",消费";
                                    }
                                    else
                                    {
                                        so.MapUsing += "消费";
                                    }
                                   
                                }
                                if (item1.WaltUsing.Substring(2, 1) == "1")
                                {
                                    if (so.MapUsing != "")
                                    {
                                        so.MapUsing += ",提现 ";
                                    }
                                    else
                                    {
                                        so.MapUsing += "提现 ";
                                    }
                                    
                                }
                                if (item1.WaltUsing.Substring(3, 1) == "1")
                                {

                                    if (so.MapUsing != "")
                                    {
                                        so.MapUsing += ",转移 ";
                                    }
                                    else
                                    {
                                        so.MapUsing += "转移 ";
                                    }
                                   
                                }
                            }
                        }
                        so.WaltID = item1.WaltID;
                        so.WaltName = item1.WaltName;
                        so.WaltDep = item1.WaltDep;
                        so.WaltMer = item1.WaltMer;
                        so.WaltUsing = item1.WaltUsing;
                        so.WaltRec = item1.WaltRec;
                        so.WaltMax = item1.WaltMax;
                        so.WaltLastTime = item1.WaltLastTime;
                        so.WaltLastOper = item1.WaltLastOper;
                        so.WaltState = item1.WaltState;
                        List.Add(so);
                    }
                }
                else
                {
                    return null;
                }
                  
                  
                    jqgridparam.records = List.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),

                        rows = FindListPage(List, ref jqgridparam)//返回当前页的数据
                        //row = List
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = List
                    };
                    return Json(data);
                }
            }
            catch (Exception)
            {
                return null;
            }

        }
        #endregion



        #region 保存钱包信息
        /// <summary>
        /// 保存钱包信息
        /// </summary>
        /// <param name="Tag">更新类型（1：增，2：改，3：删除）</param>
        /// <param name="model">更新数据</param>
        /// <returns></returns>
        public ActionResult SetOrderWalt(int Tag, Model.Order_Walt_T model)
        {

            // 获取操作员
            operUser = Session[SessionStorage.OperUser] as Model.View_OperUser;
            if (operUser != null)
            {
                try
                {
                    if (Tag != 1)
                    {
                        model.WaltLastOper = operUser.OperID;
                        model.WaltLastTime = new DateTimeHelper().getDateTimeNow();
                        model.WaltMax = model.WaltMax + "00";
                        string info = ObjectToJson(model);
                        string result = SRS.SetOrder_Walt(operUser.OperID, info, Tag, "", 1);//从接口获得所有流水
                        JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                        string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                        if (bs == "1")//返回结果正常
                        {
                            return Json(bs);
                        }
                        else
                        {
                            return Json(searcho["MSG"].ToString());
                        }
                    }
                    else
                    {
                    #region 
                    //判断钱包的唯一性
                    List<Model.Order_Walt_T> List = new List<Model.Order_Walt_T>();
                    string result1 = SRS.GetOrder_Walt(YZM, 1);
                    JObject searcho1 = JObject.Parse(result1);//将服务返回的结果进行优化
                    string bs1 = searcho1["BS"].ToString();//获取返回结果是否正常标识
                    if (bs1 == "1")//返回结果正常
                    {
                        int i = 1;
                        IList<JToken> jieguo = searcho1["rows"].Children().ToList();//解析返回的结果
                        List = ParseClass<Model.Order_Walt_T>.JsonList(jieguo);//解析返回的结果
                        foreach (Model.Order_Walt_T item in List)
                        {
                            if (model.WaltName == item.WaltName)
                            {
                                i += 1;
                            }
                        }
                        if (i == 1)
                        {
                            model.WaltLastOper = operUser.OperID;
                            model.WaltLastTime = new DateTimeHelper().getDateTimeNow();
                            model.WaltMax = model.WaltMax + "00";
                            string info = ObjectToJson(model);
                            string result = SRS.SetOrder_Walt(operUser.OperID, info, Tag, "", 1);//从接口获得所有流水
                            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                            if (bs == "1")//返回结果正常
                            {
                                return Json(bs);
                            }
                            else
                            {
                                return Json(searcho["MSG"].ToString());
                            }
                        }
                        else
                        {
                            return Json("2");
                        }
                    }
                    else
                    {
                        model.WaltLastOper = operUser.OperID;
                        model.WaltLastTime = new DateTimeHelper().getDateTimeNow();
                        model.WaltMax = model.WaltMax + "00";
                        string info = ObjectToJson(model);
                        string result = SRS.SetOrder_Walt(operUser.OperID, info, Tag, "", 1);//从接口获得所有流水
                        JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                        string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                        if (bs == "1")//返回结果正常
                        {
                            return Json(bs);
                        }
                        else
                        {
                            return Json(searcho["MSG"].ToString());
                        }

                    }
                    #endregion


                    }
                }
                catch (Exception e)
                {
                    string error = e.Message;
                    return Json(error);
                }
            }
            else
            {
                //return Json("获取操作员出错！");             
                return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                
            }
        }
        #endregion

        #region 获取第三方列表
        /// <summary>
        /// 获取第三方列表
        /// </summary>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult GetThridPay()
        {
            try
            {
                List<Model.Order_Pay_T> List = new List<Model.Order_Pay_T>();
                string result = SRS.GetOrder_Pay(YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    List = ParseClass<Model.Order_Pay_T>.JsonList(jieguo);//解析返回的结果
                    return Json(List, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception)
            {
                return null;
            }

        }
        #endregion

        #region 获取商户列表
        /// <summary>
        /// 获取商户列表
        /// </summary>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult GetOrderMer()
        {
            try
            {
                List<Model.View_Order_MerSet> List = new List<Model.View_Order_MerSet>();
                string result = SRS.GetOrder_Mer(YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    List = ParseClass<Model.View_Order_MerSet>.JsonList(jieguo);//解析返回的结果
                    return Json(List, JsonRequestBehavior.AllowGet);
                    //return Content(List.TreeToJson());
                }
                else
                {
                    return null;
                }
            }
            catch (Exception)
            {
                return null;
            }

        }
        #endregion

        #region 获取组织结构列表
        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        public ActionResult getDep()
        {
            try
            {
                Model.View_OperUser operUser = Session[SessionStorage.UserLogin] as Model.View_OperUser;
                List<TreeJsonEntity> TreeList = new List<TreeJsonEntity>();
                string result = zhhqser.GetDepatMentNoValidate("", 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                List<Basic_Department_T> ls = new List<Basic_Department_T>();
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() == "1")//返回结果正常
                {
                    IList<JToken> jieguo = jb["rows"].Children().ToList();
                    ls = ParseClass<Basic_Department_T>.JsonList(jieguo);//解析返回的结果
                    foreach (Basic_Department_T item in ls)
                    {
                        bool hasChildren = false;
                        IList childnode = ls.FindAll(t => t.DepParentID == item.DepID);
                        if (childnode.Count > 0)
                        {
                            hasChildren = true;
                        }
                        TreeJsonEntity tree = new TreeJsonEntity();
                        tree.id = item.DepID;
                        tree.text = item.DepName;
                        tree.value = item.DepID;
                        tree.isexpand = true;
                        tree.complete = true;
                        tree.hasChildren = hasChildren;
                        tree.parentId = item.DepParentID;
                        TreeList.Add(tree);
                    }
                    string a = TreeList.TreeToJson();
                    return Content(TreeList.TreeToJson());
                }
                else
                {
                    return Json(jb["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion 

        //补充钱包列表说明
        public class Order_Walt_SA
        {

            public string WaltID { get; set; }
            public string WaltName { get; set; }
            public string WaltDep { get; set; }
            public string WaltMer { get; set; }
            public string WaltUsing { get; set; }
            public string WaltRec { get; set; }
            public string WaltMax { get; set; }
            public string WaltLastTime { get; set; }
            public int WaltLastOper { get; set; }
            public Nullable<int> WaltState { get; set; }
            public string PayName { get; set; } //显示支付名
            public string MapUsing { get; set; }
        }

        #region 获取当前页数据
        /// <summary>
        /// 获取当前页数据
        /// </summary>
        /// <param name="list">总的list数据</param>
        /// <param name="jqgridparam">分页参数</param>
        /// <returns></returns>
        public List<Order_Walt_SA> FindListPage(List<Order_Walt_SA> list, ref JqGridParam jqgridparam)
        {
            try
            {
                List<Order_Walt_SA> RetList = new List<Order_Walt_SA>();
                string orderField = jqgridparam.sort;//排序列
                string orderType = jqgridparam.order;//排序方式
                int pageIndex = jqgridparam.page;//当前页
                int pageSize = jqgridparam.rows;//每页行数
                int totalRow = jqgridparam.records;//总记录数
                int lastIndex = pageIndex * pageSize;//当前页最后一行
                if (orderType == "asc")
                {
                    list = (from p in list orderby orderField ascending select p).ToList();
                }
                else if ((orderType == "desc"))
                {
                    list = (from p in list orderby orderField descending select p).ToList();
                }

                //如果总行数小于当前页最后一行时 当前页最后一行等于总行数
                if (totalRow < lastIndex)
                {
                    lastIndex = totalRow;
                }
                int fistIndex = (pageIndex - 1) * pageSize;
                int j = 0;
                for (int i = fistIndex; i < lastIndex; i++)
                {
                    j++;
                    RetList.Add(list[i]);
                }
                return RetList;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion
    }
}
